var Lottery = Lottery || {};
//奖项人数
Lottery.number = 0;
Lottery.isStartLottery = false;
//获奖的名单
Lottery.Winners = [];
//服务端的配置信息
Lottery.setting = [];
//奖项类型
Lottery.type = -1;
//签到的人的数据
Lottery.signPersonArray = [];

//抽奖盒子数组，存的是每个盒子对应的定时器动画和中奖人信息；
Lottery.cardAnimation = [];
Lottery.cardAnimationIndex = 0;

Lottery.isOpenLottery = false;

Lottery.ranks = {};



//能够抽奖的队列数据（即排除了获奖人的数组）
Lottery.canLotteryArray = [];



Lottery.setting = [
        {
            name:'一等奖',
            num:1
        },
        {
            name:'二等奖',
            num:2
        },
        {
            name:'三等奖',
            num:3
        },
        {
            name:'四等奖',
            num:4
        },
        {
            name:'五等奖',
            num:5
        }
    ];



Lottery.onEvent = function (number,type) {
    Lottery.number = Lottery.setting[type].num;
    Lottery.type = type;
    Lottery.cardAnimation = [];
    Lottery.getLotterySetting();
    Lottery.startAnimation();

};

Lottery.init = function () {
     Lottery.Winners = [];
     Lottery.signPersonArray = [];
     Lottery.cardAnimation = [];
     Lottery.canLotteryArray = [];
    Lottery.getLotterySetting();
    Lottery.getSignPersonInfo();
    Lottery.getAllPersonInfo();
}

Lottery.exitEvent = function () {
    Lottery.setting = {} ;
    Lottery.Winners = [];
    Lottery.isStartLottery = false;
    Lottery.number = 0;
    Lottery.cardAnimation = [];
    Lottery.onReFresh();
    Lottery.type = -1;
    $(".lotteryshow").css('visibility','hidden');
    // $('.earththreeanimation').css('visibility','hidden');
};

//进入抽奖模式后显示背景动画
Lottery.showBgAnimation = function () {
    // $('.earththreeanimation').css('visibility','visible');
};

//开始抽奖动画
Lottery.startAnimation = function () {
    Lottery.isStartLottery = true;
    $(".lotteryresult").css('visibility','hidden');
    $(".lotteryshow").css('visibility','visible');
    $(".lotteryshow").text(""+Lottery.setting[Lottery.type].name);
    Lottery.show321Num();
    setTimeout(function () {
        Lottery.showRandomPicTest();
    },3800)
};

Lottery.onReFresh = function () {

    var resultDom = document.getElementById('lotteryresultid');
    var childs = resultDom.childNodes;
    for (var i = (childs.length - 1); i >= 0; i--) {
        resultDom.removeChild(childs[i]);
    }
};

Lottery.showResult = function () {
    if(Lottery.number <= 0){
        return;
    }

    $(".lotteryshow").stop(true,false);
    $(".lotteryshow").text("恭喜获奖");

    //这一轮结束，可以重新开始了；
    Lottery.isStartLottery = false;
    Lottery.number = 0;
};

function createCard() {
    var card = $('<div>');
    card.addClass('recordcard');
    if(Lottery.number <=6 ){
        card.css('font-size','20px');
    }
    card.html($('#avard-record-card-tmpl').html());
    card.find('.photo').attr('src',  '/static/images/default.jpg');
    card.find('.photo').addClass("recordphoto");
    card.find('.textdes').addClass('recordcardtextdes');
    card.find('.greetings').addClass('recordcardgreetings');
    card.find('.description').addClass('recordcarddescription');
    return card;
}
/*
function addPicToContainer(container) {
    for(var i = 0 ; i < Lottery.signPersonArray.length; i++){
        var d = Lottery.signPersonArray[i];
        container.append(createCard(d));
    }
    container.prepend(createCard(Lottery.signPersonArray[Lottery.signPersonArray.length-1]));
    return container;
}

Lottery.showLoopPic = function() {
    Lottery.onReFresh();
    $(".lotteryresult").css('visibility','visible');
    var resultDom = document.querySelector(".lotteryresult");
    var x = 0;
    var y = 0;
    var cardX = 5;
    var cardY = 5;

    for(var i = 0 ; i < Lottery.number ; i++) {
        var cardContainter = addPicToContainer($('<div>'));
        cardContainter.addClass('lotteryboxcontainer');

        var cardBox = $('<div>');
        cardBox.addClass('lotterybox');
        cardBox.append(cardContainter);

        var pichead = cardBox[0];
        var picheadJQ = $(pichead);

        if (Lottery.number >= 8) {

            if ($(resultDom).width() * ((cardX + 15) / 100) < $(resultDom).width()) {
                picheadJQ.css('left', cardX + '%').css('top', cardY + '%');
                cardX += 13;
            } else {
                cardX = 5;
                if ($(resultDom).height() * ((cardY + 56) / 100) < $(resultDom).height()) {
                    cardY += 28;
                } else {
                    cardY = 5;
                }
                picheadJQ.css('left', cardX + '%').css('top', cardY + '%');
                cardX += 13;
            }
            $(resultDom).css({
                width: '100%',
                height: '100%',
                left: '0%',
                top: '0%'
            });
        } else {
            y = 30;
            x = (6 - Lottery.number) / 2 * 16;
            $(resultDom).css({
                width: ((i + 1) * 16) + '%',
                height: '35%',
                left: x + '%',
                top: y + '%'
            });
            cardX = i * (100 / Lottery.number);
            cardBox.css('width', (($(resultDom).width() / Lottery.number) / $(resultDom).width() * 100) + "%").css('height', '100%');
            picheadJQ.css('left', cardX + '%').css('top', cardY + '%');
        }
        resultDom.appendChild(pichead);
        showCardFlow(cardContainter);
    }

}*/


Lottery.showRandomPicTest = function() {
    Lottery.onReFresh();
    $(".lotteryresult").css('visibility','visible');
    var resultDom = document.querySelector(".lotteryresult");
    var x = 0;
    var y = 0;

    var n = Lottery.ranks.row;
    var m = Lottery.ranks.column;

    var cardXInit = 2;
    var cardXwidth = (100-2*cardXInit)/m;
    var cardYHeight = cardXwidth*19.5/9;
    var cardYInit = (100-(n*cardYHeight))/2;



    var cardX = cardXInit;
    var cardY = cardYInit;

    for(var i = 0 ; i < Lottery.number ; i++) {

        var cardBox = $('<div>');
        cardBox.addClass('lotterybox');
        cardBox.css({'width':cardXwidth+"%",'height':cardYHeight+"%"});
        cardBox.append(getRandCandContent());

        var pichead = cardBox[0];
        var picheadJQ = $(pichead);

        if (Lottery.number >= 8) {
            if(cardX+cardXwidth <= (100-cardXInit) ) {
                picheadJQ.css('left', cardX + '%').css('top', cardY + '%');
                cardX += cardXwidth;
            } else {
                cardX = cardXInit;
                if(cardY+cardYHeight <= (100-cardYInit)) {
                    cardY += cardYHeight;
                } else {
                    cardY = cardYInit;
                }
                picheadJQ.css('left', cardX + '%').css('top', cardY + '%');
                cardX += cardXwidth;
            }
            $(resultDom).css({
                width: '100%',
                height: '100%',
                left: '0%',
                top: '0%'
            });
        } else {
            y = 30;
            x = (6 - Lottery.number) / 2 * 16;
            $(resultDom).css({
                width: ((i + 1) * 16) + '%',
                height: '35%',
                left: x + '%',
                top: y + '%'
            });
            cardX = i * (100 / Lottery.number);
            cardBox.css('width', (($(resultDom).width() / Lottery.number) / $(resultDom).width() * 100) + "%").css('height', '100%');
            picheadJQ.css('left', cardX + '%').css('top', cardY + '%');
        }
        resultDom.appendChild(pichead);
    }
}


Lottery.getLotterySetting = function () {
    $.ajax({
        url: '/overview/getlotterysetting',
        method: 'GET',
    }).done(function (response) {
        if (response.code === 0) {
            Lottery.setting = JSON.parse(response.data).setting;
            Lottery.ranks = JSON.parse(response.data).ranks;
        } else {
        }
    });
};

Lottery.saveWinnersInfo = function () {
    //同时把抽奖盒子数组也重置
    Lottery.cardAnimation = [];
    Lottery.cardAnimationIndex = 0;

    // var finalwinners = Lottery.allPersonArray.filter(function (x) {
    //     for(var i = 0; i< Lottery.Winners.length ; i++){
    //         if(x.id === Lottery.Winners[i].id && x.company_id===Lottery.Winners[i].company_id){
    //             return true;
    //         }
    //     }
    //     return false;
    // });

    var finalwiners = [];
    for(var i = 0; i<Lottery.Winners.length; i++){
        if(Lottery.Winners[i].company_id === 1){
            finalwiners.push(Lottery.Winners[i]);
        }else{
            for(var j = 0; j < Lottery.allPersonArray.length; j++){
                if(Lottery.Winners[i].id === Lottery.allPersonArray[j].id){
                    var d = Lottery.allPersonArray[j];
                    d.lottery = Lottery.Winners[i].lottery;
                    finalwiners.push(d);
                    break;
                }
            }
        }
    }

    // finalwiners.map(function (x) {
    //     for(var i = 0; i< Lottery.Winners.length ; i++){
    //         if(x.id === Lottery.Winners[i].id && x.company_id===Lottery.Winners[i].company_id){
    //             x.lottery = Lottery.Winners[i].lottery;
    //             return x;
    //         }
    //     }
    // })

    $.ajax({
        url: '/overview/saveLotteryWinners',
        method: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(finalwiners)
    }).done(function (response) {
        console.log('save succeed');
        if (response.code === 0) {
        } else {
        }
    });
}

Lottery.getSignPersonInfo = function () {
    $.ajax({
        url: '/overview/getSignPersonInfo',
        method: 'GET'
    }).done(function (response) {
        console.log(response);
        if (response.code === 0) {
            Lottery.signPersonArray = response.data;
            Lottery.getWinnersInfo();
        } else {
        }
    });
};

Lottery.getWinnersInfo = function () {
    $.ajax({
        url: '/overview/getLotteryWinnersInfo',
        method: 'GET'
    }).done(function (response) {
        if (response.code === 0) {
            Lottery.Winners = response.data;
            refreshLotteryArray();
        } else {
        }
    });
};



/*//显示卡片闪动，需要传入一个容器,一个包含很多图片的容器
function showCardFlow(content) {
    isStopCardLoop = false;
    var childrenheight = $(content.children()[0]).height();
    var childNum = content.children().length;

    var imglastsecond_y = -(childrenheight * (childNum - 1));//倒数第一个子元素的左上角y坐标
    content.css('top', imglastsecond_y+"px");//初始化移动到倒数第一个
    var next = imglastsecond_y + childrenheight;//下一步要移动到倒数第二个
    var i = childNum - 2;

    function scrollToBottom(argument) {
        content.animate({
            'top': next+'px'
            },100, function() {
                if(isStopCardLoop){
                    next+=childrenheight;
                    showFinalResult(content,next);
                    Lottery.saveWinnersInfo(i);
                    return;
                }

                if(i===0){
                    //移动到了顶部，顶部和倒数第一个是一样的，所以应该直接跳到倒数第一个再进行下一轮循环；
                    content.css('top',imglastsecond_y+'px');//重新移动到倒数第一个
                    next = imglastsecond_y+childrenheight;//下一步就是倒数第二个
                    i = childNum-2;//i也重新回到初始
                    scrollToBottom();
                }else{
                    i -=1;
                    next+=childrenheight;
                    scrollToBottom();
                }
        });
    }
    scrollToBottom();
}*/

function showFinalResult(content, next) {
    content.animate({
        'top': next+'px'
    },3000);
}


function show321() {
    console.log('show321');
    $(".lotteryshow").append("<div class='cell'><div class='num'>3 2 1 0</div></div>");
    setTimeout(function () {
        $('.cell').remove();
    }, 4000);
}


function getRandCandContent() {

    //创建一个装载头像的容器（只装一个）
    var cardContent = $('<div>');
    cardContent.addClass('lotteryboxcontainer');
    cardContent.append(createCard());

    var cardBoxInfo = {
        picInterval:'',mark:{}
    }

    cardBoxInfo.picInterval = setInterval(function () {
        var k = getRandom(0,Lottery.canLotteryArray.length);
        cardBoxInfo.mark = Lottery.canLotteryArray[k] || {} ;
        $(cardContent[0]).find('.photo').attr('src', typeof(Lottery.canLotteryArray[k].avatar) == 'undefined'? "/static/images/default.jpg" : Lottery.canLotteryArray[k].avatar);
        $(cardContent[0]).find('.textdes').text(typeof(Lottery.canLotteryArray[k].name) == 'undefined'? "" : Lottery.canLotteryArray[k].name);
        $(cardContent[0]).find('.greetings').text(typeof(Lottery.canLotteryArray[k].department) == 'undefined'? "" : Lottery.canLotteryArray[k].department);
        $(cardContent[0]).find('.greetings').text(typeof(Lottery.setting[Lottery.type].name) == 'undefined'? "" : Lottery.setting[Lottery.type].name);
    },100);
    Lottery.cardAnimation[Lottery.cardAnimationIndex] = cardBoxInfo;
    Lottery.cardAnimationIndex++;
    return cardContent;
};

Lottery.stopRandomPicAnimation = function () {

    var k = 0;
    function clearAnimation() {
        if(k < Lottery.cardAnimation.length){
            if(!Lottery.cardAnimation[k].mark){
                return;
            }
            if(!checkLottery(Lottery.cardAnimation[k].mark)){//检查是否已经中奖，
                //保存中奖信息
                Lottery.cardAnimation[k].mark.lottery = Lottery.setting[Lottery.type].name;
                Lottery.Winners.push(Lottery.cardAnimation[k].mark);
                //停止定时器函数执行
                clearInterval(Lottery.cardAnimation[k].picInterval);
                k ++;
                clearAnimation();
                refreshLotteryArray();//刷新抽奖队列；
            }else{
                setTimeout(function () {
                    clearAnimation();
                },100);
            }
        }else{//这一轮所有抽奖盒子动画都已经走完，保存好中奖信息；
            Lottery.saveWinnersInfo();
        }
    }
    setTimeout(clearAnimation,100);
};

// function clearAllAnimation() {
//     for(var i = 0 ; i < Lottery.cardAnimation.length; i++){
//         clearInterval(Lottery.cardAnimation[i].picInterval);
//     }
//     Lottery.cardAnimation = [];
// }


function getRandom(n,m) {
    return Math.floor((Math.random() * (m - n) + n));
}

function refreshLotteryArray() {
    Lottery.canLotteryArray = Lottery.signPersonArray.filter(function (x) {
        for(var i = 0; i < Lottery.Winners.length; i++){
            if(x.id === Lottery.Winners[i].id){
                return false;//如果有相等的，就不保存，过滤掉
            }
        }
        return true;
    })
}

function checkLottery(d) {
    for(var i = 0; i < Lottery.Winners.length; i++){
        if(d.id === Lottery.Winners[i].id){
            return true;
        }
    }
    return false;
}


Lottery.saveSignPersonInfo = function () {
    $.ajax({
        url: '/overview/saveSignPersonInfo',
        method: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(Lottery.signPersonArray.map(function (x) {
            x.src = '';
            return x;
        }))
    }).done(function (response) {
        if (response.code === 0) {
        } else {
        }
    });
}

Lottery.show321Num = function () {
    $('.shownum').css('display','inline');
    var k = 3;
    function shownumpic() {
        if(k >= 0){
            $('.shownum').css('background-image','url(/static/lotterydir/img/'+k+'.png)');
            k--;
            setTimeout(function () {
                shownumpic();
            },1000)
        }else {
            $('.shownum').css('display','none');
        }
    }
    shownumpic();
}


Lottery.getAllPersonInfo = function () {
    $.ajax({
        url: '/subject/list?category=employee&size=2000&_=1515400799648',
        method: 'GET'
    }).done(function (response) {
        if (response.code === 0) {
            Lottery.allPersonArray = response.data;
            $.ajax({
                url: '/overview/saveallperson',
                method: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(Lottery.allPersonArray)
            }).done(function (response) {

            });
        } else {

        }
    });
}


/*Lottery.saveFinalSignInfo = function () {
    var signsavearray = Lottery.allPersonArray.filter(function (x) {
        for(var i = 0; i< Lottery.signPersonArray.length ; i++){
            if(x.id === Lottery.signPersonArray[i].id){
                return true;
            }
        }
        return false;
    });

    $.ajax({
        url: '/overview/saveSignPersonInfo',
        method: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(signsavearray)
    }).done(function (response) {
        if (response.code === 0) {
        } else {
        }
    });
}*/
